#include "qETMvnes.h"
#include <QItemSelectionModel>
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlRecord>
#include <QSqlError>
#include "chelperclass.h"
#include <QLocale>
#include "sterna.h"
#include <QDesktopWidget>


QETMVnes::QETMVnes(QWidget *parent)
	: QMyBaseFormWidget(parent)
    , selRow(-1)
    , textId("")
    , komintentID("")
    , artikal_sifra("")
    , pItemDelegate(0)
    , editorOpen(0)
	,requestfromKomintent(0)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.lineEdit->setFocus();
    ui.lineEdit->setText("");
    ui.lineEdit->selectAll();
    ui.lineEdit_2->setText("");
    ui.lineEdit->setStyleSheet("background-color: yellow");
    ui.lineEdit->installEventFilter(this);
    ui.lineEdit_2->installEventFilter(this);
    ui.lineEdit_3->installEventFilter(this);
    ui.lineEdit_4->installEventFilter(this);
	ui.lineEdit_6->installEventFilter(this);

	ui.dateTimeEdit->installEventFilter(this);
    connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(on_pushButton1AA_clicked()));
    connect(ui.lineEdit_8, SIGNAL(returnPressed()), this, SLOT(on_pushButton1AA8_clicked()));
	connect(ui.lineEdit_2, SIGNAL(returnPressed()), this, SLOT(on_pushButton2AAA_2_clicked()));
    connect(ui.lineEdit_3, SIGNAL(returnPressed()), this, SLOT(on_plineEdit3_Pressed()));
    connect(ui.lineEdit_5, SIGNAL(returnPressed()), this, SLOT(on_plineEdit4_Pressed()));
    connect(ui.lineEdit_6, SIGNAL(returnPressed()), this, SLOT(on_plineEdit6_Pressed()));
	connect(ui.lineEdit_12, SIGNAL(returnPressed()), this, SLOT(on_plineEdit12_Pressed()));

	connect(ui.lineEdit_3, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_5, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_12, SIGNAL(editingFinished()), this, SLOT(updateModelData()));


	ui.dateTimeEdit->setDate(QDate::currentDate());
	ui.dateTimeEdit_2->setDate(QDate::currentDate());
    pItemDelegate = new QSTableWidgetDelegate(ui.tableView);
    connect(this ,SIGNAL(editCell()),this,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this,SLOT(closeEditor()));
	connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(callImportIspratnici()));

    ui.tableView->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui.tableView->setItemDelegate(pItemDelegate);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));


	model = new QStandardItemModel(0, 11);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("1\nШифра."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("2\nНазив на\nСтоките"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("3\nЕдинечна\nмера"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("4\nКол*"));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("5\nЕдин.Цена"));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("6\nИзнос*(4х5)"));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("7\nДДВ при\nНабавка"));
	model->setHeaderData( 7, Qt::Horizontal, trUtf8("8\nПропишана\nстапка ДДВ"));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("9\nЕдин.Цена"));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("10\nИзнос*(4х9)"));
	model->setHeaderData( 10, Qt::Horizontal, trUtf8("11\nВкупен ДДВ\nво прод. вредн"));


    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
    header->show();
}

void QETMVnes::pressF9()
{
	on_pushButton_4_clicked();
}


void QETMVnes::pressEscape()
{
    emit closeW();
}
void QETMVnes::setKomintent(QString text, QString textName)
{
    if(requestfromKomintent == 1)
	{
		ui.lineEdit->setText(textName);
		komintentID = text;
	}
	if(requestfromKomintent == 2)
	{
		ui.lineEdit_8->setText(textName);
		prodavnicaID = text;
	}

}

void QETMVnes::setFocusLine()
{
	if (requestfromKomintent == 1)
	{
		ui.lineEdit_8->setFocus();
		ui.lineEdit_8->selectAll();
	}
	if (requestfromKomintent == 2)
	{
		ui.lineEdit_2->setFocus();
		ui.lineEdit_2->selectAll();
	}
}

void QETMVnes::setArtikli(QString text, QString textName)
{
    ui.lineEdit_2->setText(textName);
    textId = text;
    artikal_sifra = text;

    QSqlQuery query;
    query.prepare("select edm, ddv from artikli where id = :id");
    query.bindValue(":id", artikal_sifra);	
    query.exec();
    query.next();
    ui.lineEdit_9->setText(query.value(0).toString());
	ui.lineEdit_10->setText(query.value(1).toString());
}
void QETMVnes::setSaldo(QString text)
{
    ui.lineEdit_5->setText(text);
}

void QETMVnes::setFocusLine2()
{
    ui.lineEdit_3->setFocus();
    ui.lineEdit_3->selectAll();

}


void QETMVnes::on_pushButton1AA_clicked()
{
    requestfromKomintent = 1;
	CHelperClass hclass(this);
    if (!hclass.isKomintentExists(ui.lineEdit->text()))
    {
        emit scallKomintenti((QWidget*)this, ui.lineEdit->text());
    }
    else
    {
        ui.lineEdit_8->setFocus();
    }
}

void QETMVnes::on_pushButton1AA8_clicked()
{
	requestfromKomintent = 2;
	CHelperClass hclass(this);
	if (!hclass.isKomintentExists(ui.lineEdit_8->text()))
	{
		emit scallKomintenti((QWidget*)this, ui.lineEdit_8->text());
	}
	else
	{
		ui.lineEdit_2->setFocus();
	}
}


void QETMVnes::lineEditPressReturn()
{
    emit scallKomintenti((QWidget*)this, ui.lineEdit->text());
}

void QETMVnes::on_pushButton2AAA_2_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit_2->text());
    }
    else
    {
        ui.lineEdit_3->setFocus();
    }
}

void QETMVnes::on_pushButton_3_clicked()
{
	CHelperClass hclass(this);
	if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_2->setFocus();
		return;
	}


	QLocale loc;
	if(textId.toInt() == -1)
	{
		return;
	}

	//m_id = textId.toInt();

	QString temp = "select id, sifra, artikal, edm, ddv from artikli where id =";
	temp += textId;
	QSqlQuery query(temp);
	QString country1 = "";
	QString country2 = "";
	QString country3 = "";
	QString country4 = "";
	QString country5 = "";

	while (query.next()) {
		country1 = query.value(query.record().indexOf("id")).toString();
		country2 = query.value(query.record().indexOf("sifra")).toString();
		country3 = query.value(query.record().indexOf("artikal")).toString();
		country4 = query.value(query.record().indexOf("edm")).toString();
		country5 = query.value(query.record().indexOf("ddv")).toString();
		//        ui.lineEdit->setText(country1);
	}

	int row = model->rowCount();

	QStandardItem *item = new QStandardItem(country1);
	item->setEditable(false);
	item->setTextAlignment(Qt::AlignRight);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(0, 50);
	model->setItem(row, 0, item);

	item = new QStandardItem(country3);
	item->setTextAlignment(Qt::AlignLeft);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(1, 200);
	model->setItem(row, 1, item);

	item = new QStandardItem(country4);
	item->setTextAlignment(Qt::AlignLeft);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 50);
	model->setItem(row, 2, item);

	item = new QStandardItem(ui.lineEdit_3->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 3, item);

	item = new QStandardItem(ui.lineEdit_4->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 4, item);

	item = new QStandardItem(ui.lineEdit_5->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 5, item);

	item = new QStandardItem(ui.lineEdit_6->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 6, item);

	item = new QStandardItem(ui.lineEdit_10->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 7, item);

	item = new QStandardItem(ui.lineEdit_11->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 8, item);

	item = new QStandardItem(ui.lineEdit_12->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 9, item);

	item = new QStandardItem(ui.lineEdit_13->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 10, item);


	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();

	ui.lineEdit_2->setStyleSheet(QString( "background-color: none"));
	ui.lineEdit_2->setText("");
	ui.lineEdit_3->setText("");
	ui.lineEdit_4->setText("");
	ui.lineEdit_5->setText("");
	ui.lineEdit_6->setText("");
	ui.lineEdit_9->setText("");
	ui.lineEdit_10->setText("");
	ui.lineEdit_11->setText("");
	ui.lineEdit_12->setText("");
	ui.lineEdit_13->setText("");

	ui.lineEdit_2->setFocus();

	textId = "-1";
	//	calculate();
}
void QETMVnes::selectionChanged(QModelIndex modelX,QModelIndex modelY)
{
    selRow = modelX.row();
    editorOpen = false;
    emit closeCell();
}

void QETMVnes::on_pushButton_6_clicked()
{
    model->removeRow(selRow);
	calculate();
}
void QETMVnes::pressReturn()
{
    if (ui.pushButton_3->hasFocus())
    {
        on_pushButton_3_clicked();
    }
    else if (ui.pushButton_6->hasFocus())
    {
        on_pushButton_6_clicked();
    }
    else if (ui.tableView->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
        }
        else
        {
            emit editCell();
        }
        editorOpen = !editorOpen;
    }
}


void QETMVnes::on_pushButton_4_clicked()
{
	QLocale loc;
	if (!validateKomintent())
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за коминтент е невалиден\nОдбери коминтент од листата на коминтенти!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit->setFocus();
		return;
	}
	
	int cols = model->columnCount();
    int rows = model->rowCount();
    if (!rows)
    {
        return;
    }

    int mid=0;
	QSqlDatabase db = QSqlDatabase::database();
	db.transaction();	

	bool sqlStat = true;

		int m_id_prod = 1;
		QString tempProd = "select max(dok_id_prodavnica) from dokumenti_prodavnica where dok_tip = 20 and prodavnica_id = "+prodavnicaID;
		QSqlQuery query5(tempProd);
		
		while (query5.next()) 
		{
			m_id_prod = query5.value(0).toInt() + 1;
		}

		int m_id = 1;
        QString temp = "select max(dok_id) from dokumenti_prodavnica where dok_tip = 20";
        QSqlQuery query(temp);
        QString country1 = "";
        int fieldNo = query.record().indexOf("max(dok_id)");
        while (query.next()) 
		{
            m_id = query.value(0).toInt() + 1;
        }

        int row = model->rowCount();

        query.clear();
        query.prepare("insert into dokumenti_prodavnica(dok_id, dok_tip, datum, faktura_id, mag_id, komintent_id, datum_plakanje, prodavnica_id, dok_id_prodavnica) values(:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9)");
        query.bindValue(":a1", m_id);	
        query.bindValue(":a2", 20);	
        query.bindValue(":a3", ui.dateTimeEdit->date().toString("yyyy-MM-dd"));	
        query.bindValue(":a4", 0);	
        query.bindValue(":a5", 0);	
        query.bindValue(":a6", komintentID);	
		query.bindValue(":a7", ui.dateTimeEdit_2->date().toString("yyyy-MM-dd"));	
        query.bindValue(":a8", prodavnicaID);	
		query.bindValue(":a9", m_id_prod);	
		sqlStat = sqlStat && query.exec();

        query.clear();
        query.prepare("select max(id)mid from  dokumenti_prodavnica");
        query.exec();
		sqlStat = sqlStat && query.exec();

        for (int i = 0; i < rows; i++)
        {

            QString mTipDok = "P";
            QString mEmpty ="Empty";
            QString mArtikalID = model->item(i, 0)->text();
            QString mArtikalArtikal = model->item(i, 1)->text();
            QString mArtikalEdm = model->item(i, 2)->text();
			QString mKol = model->item(i, 3)->text();
			QString mEdinecna_nabavna_cena = model->item(i, 4)->text();
            QString mIznos_nabavna = model->item(i, 5)->text();
			QString mDDV_nabavna = model->item(i, 6)->text();
			QString mStapka_ddv = model->item(i, 7)->text();
			QString mEdinecna_prodazna_cena = model->item(i, 8)->text();
			QString mIznos_prodazna = model->item(i, 9)->text();
			QString mVk_ddv_prodazna = model->item(i, 10)->text();

            query.clear();
            query.prepare(
                "insert into magacin_prodavnica(dok_id, dok_tip, artikal_id, kol, edinecna_nabavna_cena, "
				"iznos_nabavna, ddv_nabavna, stapka_ddv, edinecna_prodazna_cena, iznos_prodazna, vk_ddv_prodazna) "
				"values(:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9,:a10,:a11)"
                );

            query.bindValue(":a1", m_id);	
            query.bindValue(":a2", 20);	
            query.bindValue(":a3", mArtikalID);	
            query.bindValue(":a4", loc.toFloat(mKol));	
            query.bindValue(":a5", loc.toFloat(mEdinecna_nabavna_cena));	
			query.bindValue(":a6", loc.toFloat(mIznos_nabavna));	
			query.bindValue(":a7", loc.toFloat(mDDV_nabavna));	
			query.bindValue(":a8", loc.toFloat(mStapka_ddv));	
			query.bindValue(":a9", loc.toFloat(mEdinecna_prodazna_cena));	
			query.bindValue(":a10", loc.toFloat(mIznos_prodazna));	
			query.bindValue(":a11", loc.toFloat(mVk_ddv_prodazna));	

			sqlStat = sqlStat && query.exec();

			QSqlError err = query.lastError();
			CHelperClass chc(this);
			if (chc.isArtikalExist_CenovnikProdavnica(mArtikalID, prodavnicaID))
			{
				query.clear();
				query.prepare(
					" update magacin_prodavnica_cenovnik "
					" set prodazna_cena = :a1, ddv = :a2 "
					" where prodavnica_id = " + prodavnicaID + " and artikal_id = " + mArtikalID
					);
				query.bindValue(":a1", loc.toFloat(mEdinecna_prodazna_cena));	
				query.bindValue(":a2", loc.toFloat(mStapka_ddv));	
				sqlStat = sqlStat && query.exec();
			}
			else
			{
				query.clear();
				query.prepare(
					" insert into magacin_prodavnica_cenovnik(prodavnica_id, artikal_id, prodazna_cena, ddv) "
					" values(:a1, :a2, :a3, :a4)"
					);
 
				query.bindValue(":a1", loc.toFloat(prodavnicaID));	
				query.bindValue(":a2", loc.toFloat(mArtikalID));	
				query.bindValue(":a3", loc.toFloat(mEdinecna_prodazna_cena));	
				query.bindValue(":a4", loc.toFloat(mStapka_ddv));	
				sqlStat = sqlStat && query.exec();
			}
        }

        if (sqlStat)
        {
			db.commit();
			QMessageBox msgBox;
			msgBox.setText(trUtf8("ПЛТМ е успешно внесен."));
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setDefaultButton(QMessageBox::Ok);
			msgBox.exec();
			pressEscape();
		}
		else
		{
			db.rollback();
			QMessageBox msgBox;
			msgBox.setText(trUtf8("ПЛТМ НЕ Е внесен !!!."));
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setDefaultButton(QMessageBox::Ok);
			msgBox.exec();
		}
    
}

void QETMVnes::on_pushButton_5_clicked()
{
    pressEscape();
}


bool QETMVnes::existDok(int idDok)
{
    int nCount = 0;
    QString temp = "select count(dok_id) br from dokumenti_finansii where dok_tip = 40 and dok_id =";
    temp += QString::number(idDok, 10);
    QSqlQuery query(temp);
    QString country1 = "";
    int fieldNo = query.record().indexOf("br");
    while (query.next()) {
        nCount = query.value(0).toInt() + 1;
    }
    return nCount > 0 ? true : false;
}

bool QETMVnes::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::FocusIn)
    {
        if (object == ui.lineEdit)
        {
            ui.lineEdit->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_2)
        {
            ui.lineEdit_2->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_3)
        {
            ui.lineEdit_3->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_4)
        {
            ui.lineEdit_4->setStyleSheet("background-color: yellow");
        }
		if (object == ui.lineEdit_6)
		{
			ui.lineEdit_6->setStyleSheet("background-color: yellow");
		}
		if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: yellow");
        }
    }
    if (event->type() == QEvent::FocusOut)
    {
        if (object == ui.lineEdit)
        {
            ui.lineEdit->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_2)
        {
            ui.lineEdit_2->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_3)
        {
            ui.lineEdit_3->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_4)
        {
            ui.lineEdit_4->setStyleSheet("background-color: none");
        }
		if (object == ui.lineEdit_6)
		{
			ui.lineEdit_6->setStyleSheet("background-color: none");
		}
		if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: none");
        }
    }

    return false;
}

void QETMVnes::on_plineEdit3_Pressed()
{
	ui.lineEdit_5->setFocus();
	ui.lineEdit_5->selectAll();
}
void QETMVnes::on_plineEdit4_Pressed()
{
	if (ui.lineEdit_5->text().isEmpty())
	{

		QMessageBox msgBox;
		msgBox.setText(trUtf8("Внеси количина."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_5->setFocus();

	}
	else
	{
		ui.lineEdit_12->setFocus();
		ui.lineEdit_12->selectAll();
	}
}

void QETMVnes::on_plineEdit6_Pressed()
{
//    on_pushButton_3_clicked();
}
void QETMVnes::on_plineEdit12_Pressed()
{
	if (ui.lineEdit_12->text().isEmpty())
	{

		QMessageBox msgBox;
		msgBox.setText(trUtf8("Внеси вк. продажна цена"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_12->setFocus();
	}
	else
	{
		ui.pushButton_3->setFocus();
	}
}

void QETMVnes::openEditor()
{
    //	tableView->closePersistentEditor(indexPrev);
    QModelIndex index;
    QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
    index = indexes.at(0);	// To get the row/column numbers use 
	if ((index.column() == 3)||(index.column() == 5)||(index.column() == 9))
    {
        ui.tableView->openPersistentEditor(index);
    }
    indexPrev = index;
}

void QETMVnes::closeEditor()
{
	ui.tableView->closePersistentEditor(indexPrev);

	QStandardItem *tempKol = model->item(indexPrev.row(), 3); // kol
	QStandardItem *tempIznosNab = model->item(indexPrev.row(), 5); // iznosNabavna
	QStandardItem *tempDDV = model->item(indexPrev.row(), 7); // ddv
	QStandardItem *tempIznosProd = model->item(indexPrev.row(), 9); // ddv


	if(tempKol)
	{

		QStandardItem *temp = NULL;
		QString valueIznosNab = tempIznosNab->text(); //5
		QString valueDDV = tempDDV->text();//7
		QString valueIznosProd = tempIznosProd->text(); //9

		QLocale loc;
		float edinecnaNabCena = 0;
		float presmetanNablDDV = 0; 
		float edinecnaProdCena = 0; 
		float presmetanProdDDV = 0; 

		if(indexPrev.column() == 3)
		{
			QString valueKol = tempKol->text();  //3 fixed
			QString valueIznosNab = tempIznosNab->text(); //5
			QString valueDDV = tempDDV->text();//7
			QString valueIznosProd = tempIznosProd->text(); //9

			edinecnaNabCena = (loc.toFloat(valueIznosNab) / (loc.toFloat(valueKol))); 
			presmetanNablDDV = (loc.toFloat(valueIznosNab) * (loc.toFloat(valueDDV) / 100)); 
			edinecnaProdCena = (loc.toFloat(valueIznosProd) / (loc.toFloat(valueKol))); 

			temp = model->item(indexPrev.row(), 3);
			temp->setText(loc.toString(loc.toFloat(valueKol) , 'f', 2));
			temp = model->item(indexPrev.row(), 4);
			temp->setText(loc.toString(edinecnaNabCena , 'f', 2));
			temp = model->item(indexPrev.row(), 6);
			temp->setText(loc.toString(presmetanNablDDV , 'f', 2));
			temp = model->item(indexPrev.row(), 8);
			temp->setText(loc.toString(edinecnaProdCena , 'f', 2));
		}
		if(indexPrev.column() == 5)
		{
			QString valueKol = tempKol->text();  //3 
			QString valueIznosNab = tempIznosNab->text(); //5 fixed
			QString valueDDV = tempDDV->text();//7
			QString valueIznosProd = tempIznosProd->text(); //9

			edinecnaNabCena  = (loc.toFloat(valueIznosNab) / (loc.toFloat(valueKol))); 
			presmetanNablDDV = (loc.toFloat(valueIznosNab) * (loc.toFloat(valueDDV) / 100)); 

			temp = model->item(indexPrev.row(), 5);
			temp->setText(loc.toString(loc.toFloat(valueIznosNab) , 'f', 2));
			temp = model->item(indexPrev.row(), 4);
			temp->setText(loc.toString(edinecnaNabCena , 'f', 2));
			temp = model->item(indexPrev.row(), 6);
			temp->setText(loc.toString(presmetanNablDDV , 'f', 2));

		}
		if(indexPrev.column() == 9)
		{
			QString valueKol = tempKol->text();  //3 
			QString valueIznosNab = tempIznosNab->text(); //5 
			QString valueDDV = tempDDV->text();//7
			QString valueIznosProd = tempIznosProd->text(); //9 fixed

			edinecnaProdCena = loc.toFloat(valueIznosProd) / loc.toFloat(valueKol); 
			presmetanProdDDV = (loc.toFloat(valueIznosProd) / (1 + (loc.toFloat(valueDDV) / 100))) * (loc.toFloat(valueDDV) / 100); 

			temp = model->item(indexPrev.row(), 9);
			temp->setText(loc.toString(loc.toFloat(valueIznosProd) , 'f', 2));
			temp = model->item(indexPrev.row(), 8);
			temp->setText(loc.toString(edinecnaProdCena , 'f', 2));
			temp = model->item(indexPrev.row(), 10);
			temp->setText(loc.toString(presmetanProdDDV , 'f', 2));
		}

	}
	updateModelData();

}



QETMVnes::~QETMVnes()
{

}

bool QETMVnes::validateKomintent()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isKomintentExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}
void QETMVnes::callImportIspratnici()
{
	emit scallIspratnici((QWidget*)this, "");
}
void QETMVnes::callImportProfaktura()
{
	emit scallProfakturi((QWidget*)this, "");
}


void QETMVnes::setProfakturaID(QString text)
{
    QLocale loc;
	int r = 0;
    int c = 8;
    int fieldNo[8];
    QString country[8];
    int colWidth[] = {40, 70, 220, 60, 100, 100, 100, 100};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ddv", "ikol", "icena", "rabat" };
    QString temp = 
        "select artikli.id, sifra, artikal, edm, artikli.ddv, ikol, icena, rabat "
        "from finansovi_stavki "
        "left join artikli on finansovi_stavki.artikal_id=artikli.id "
        "where finansovi_stavki.dok_tip = 60 and finansovi_stavki.dok_id= ";
    temp += text;
    QSqlQuery query(temp);
    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    //int row = 0;
    while (query.next()) 
    {
        int row = model->rowCount();
		for (int i = 0; i < c; i++)
        {
            fieldNo[i] = query.record().indexOf(colName[i]);
            QStandardItem *item = NULL;
            QString temp = query.value(fieldNo[i]).toString();
            if (i > 3)
            {
                temp = loc.toString(temp.toFloat(), 'f', 2);
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignRight);
            }
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
    ui.lineEdit->setFocus();
	calculate();
}

void QETMVnes::setIspratnicaID(QString text)
{
	QLocale loc;

	int r = 0;
	int c = 11;
	int fieldNo[11];
	QString country[8];
	int colWidth[] = {40, 220, 80, 80, 100, 100, 100, 100, 100, 100, 100};
	QString temp = 
		"select artikli.id, artikal, edm, ikol, 0, 0, 0, artikli.ddv, 0, 0, 0  "
		"from magacin "
		"left join artikli on magacin.artikal_id=artikli.id "
		"where (magacin.dok_tip = 40 or magacin.dok_tip = 44) and magacin.dok_id= ";
	temp += text;
	QSqlQuery query(temp);

	ui.tableView->setModel(model);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
	header->show();
	//int row = 0;
	while (query.next()) 
	{
		int row = model->rowCount();
		for (int i = 0; i < c; i++)
		{
			QStandardItem *item = NULL;
			QString temp = "";
			temp = query.value(i).toString();

			if ((i > 3))
			{
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else
			{
				item = new QStandardItem(temp);
				if (i == 6)
				{
					item->setTextAlignment(Qt::AlignRight);
				}
				else
				{
					item->setTextAlignment(Qt::AlignLeft);
				}
			}

			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}        
		row++;
	} 
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
	ui.lineEdit->setFocus();
	calculate();
}

void QETMVnes::calculate()
{
	QLocale loc;
	float VKsuma = 0;
	float Iznos = 0;
	float ddv = 0;
	float kol = 0;
	float cena = 0;
	float rabat = 0;
	for (int i = 0;  i < model->rowCount(); i++)
	{
		ddv = loc.toFloat(model->item( i, 4)->text());
		kol = loc.toFloat(model->item( i, 5)->text());
		cena = loc.toFloat(model->item( i, 6)->text());
		rabat = loc.toFloat(model->item( i, 7)->text());
		Iznos = kol * cena * (1 - rabat/100);
		VKsuma += Iznos;
	}
	ui.lineEdit_7->setText(loc.toString( VKsuma, 'f', 2));
}

void QETMVnes::updateModelData()
{
	QLocale loc;
	float ddvProcent = ui.lineEdit_10->text().toFloat();

	///////////////////////Nabavna///////////////////////////////////
	float iznosNabavna = loc.toFloat(ui.lineEdit_5->text());
	float nabKol = ui.lineEdit_3->text().toFloat();
	ui.lineEdit_4->setText(loc.toString( iznosNabavna / nabKol , 'f', 2));
	float presmetanNablDDV = (iznosNabavna * (ddvProcent / 100)); 
	ui.lineEdit_6->setText(loc.toString(presmetanNablDDV , 'f', 2));

	//////////////////////Prodazna///////////////////////////////////
	
	float iznosProdazna = loc.toFloat(ui.lineEdit_12->text());
	ui.lineEdit_11->setText(loc.toString(iznosProdazna / nabKol , 'f', 2));
	float presmetanIzlDDV = (iznosProdazna / (1 + ddvProcent / 100)) * (ddvProcent / 100); 
	ui.lineEdit_13->setText(loc.toString( presmetanIzlDDV , 'f', 2));
}
